package com.an.mailserver.receiver;

import com.an.vhr.bean.Employee;

import com.an.vhr.bean.MailConstants;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.util.Date;


/**
 * @Author: an1089
 **/
@Component
public class MailReceiver {
    public static final Logger logger = LoggerFactory.getLogger(MailReceiver.class);
    @Autowired
    JavaMailSender javaMailSender;
    @Autowired
    MailProperties mailProperties;
    @Autowired
    TemplateEngine templateEngine;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @RabbitListener(queues = MailConstants.MAIL_QUEUE_NAME)
    public void handler(Message message, Channel channel) throws IOException {
        Employee employee = (Employee) message.getPayload();
        MessageHeaders headers = message.getHeaders();
        Long tag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);
        String msgId = (String) headers.get("spring_returned_message_correlation");
        if(stringRedisTemplate.opsForHash().entries("mail_log").containsKey(msgId)){
            logger.info("该消息已经被消费过");
            // 已经被消费过  无需在退回队列中
            channel.basicAck(tag, false);
            return;
        }
        MimeMessage msg = javaMailSender.createMimeMessage();
        MimeMessageHelper messageHelper = new MimeMessageHelper(msg);
        try {
            messageHelper.setTo(employee.getEmail());
            messageHelper.setFrom(mailProperties.getUsername());
            messageHelper.setSubject("入职邮件");
            messageHelper.setSentDate(new Date());
            Context context  = new Context();
            context.setVariable("name",employee.getName());
            context.setVariable("positionName",employee.getPosition().getName());
            context.setVariable("joblevelName",employee.getJobLevel().getName());
            context.setVariable("departmentName",employee.getDepartment().getName());
            String mail = templateEngine.process("mail", context);
            messageHelper.setText(mail,true);
            javaMailSender.send(msg);
            channel.basicAck(tag, false);
            stringRedisTemplate.opsForHash().put("mail_log",msgId,msgId);
            logger.info("给"+employee.getEmail()+"发送入职邮件成功");
        } catch (MessagingException e) {
            channel.basicNack(tag,false,true);
            e.printStackTrace();
            logger.error("文件发送失败！");
        }

    }
}
